﻿using AutoMapper;
using MediatR;
using ProcurementManagement.Applcation.Command.PurchaseReturnsCommand;
using ProcurementManagement.Domain.ProcurementDomain;
using ProcurementManagement.Infrstructre.Interface;
using SqlSugar;

namespace ProcurementManagement.Applcation.CommandHanlers.PurchaseReturnsCommandHandler
{
    /// <summary>
    /// 采购退款（直接退款添加）
    /// </summary>
    public class PurchaseReturnsCreateCommandHandler:IRequestHandler<PurchaseReturnsCreateCommand,int>
    {
        private readonly lnterfaceDirectRefundRepository _directRefundRepository;
        private readonly ISqlSugarClient db;
        private readonly IMapper _mapper;

        public PurchaseReturnsCreateCommandHandler(lnterfaceDirectRefundRepository directRefundRepository, ISqlSugarClient db, IMapper mapper)
        {
            _directRefundRepository = directRefundRepository;
            this.db = db;
            _mapper = mapper;
        }

        public async Task<int> Handle(PurchaseReturnsCreateCommand request, CancellationToken cancellationToken)
        {
            //开启事物
            db.Ado.BeginTran();
            try
            {
                //添加采购退款表
                var res = _mapper.Map<DirectRefund>(request.dto);
                
                var a =await _directRefundRepository.AddAsync(res);

                // 修改采购退货
                var se = await db.Queryable<PurchaseReturns>()
                         .Where(c => c.PurchaseReturnsIds == request.dto.PurchaseReturnsIds)
                         .FirstAsync();

                se.PRtotalAmount -= res.BenPrice;
                se.RefundAmoun += res.BenPrice;
                if (request.dto.SengPrice==0)
                {
                    se.PROutboundProgress = 1;
                }
                else
                {
                    se.PROutboundProgress = 2;
                }
                await db.Updateable(se).ExecuteCommandAsync();
//提交事物
                db.Ado.CommitTran();
                return 1;



            }
            catch (Exception)
            {
                //回滚事物
                db.Ado.RollbackTran();
                throw;
            }
        }
    }
}
